﻿using ConfExpert.Enums;
using DevExpress.XtraReports.UI;
using DevTeam;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;

namespace ConfExpert.Forms.Rapor
{
    public partial class Etiket : DevExpress.XtraReports.UI.XtraReport
    {
        string MyRange;
        public void Yazdir(string PrinterName)
        {
            //this.PrintingSystem.ShowMarginsWarning = false;
            this.ShowPrintMarginsWarning = false;
            this.Print(PrinterName);
        }

        public Etiket(EtiketTipi tip, string range, bool tumu = false)
        {
            InitializeComponent();

            MyRange = range;
            if (tip == EtiketTipi.RollId)
                MyRange = MakeCriteria(range);

            if (MyRange != String.Empty)
                myData1.xEtiket.Merge(Session.DataManager.ExecuteDataTable("GetBarcodes", tip, MyRange, tumu));

            //Eras Light ITC - Century - Microsoft Sans Serif

            MakeResizable(xrTableCell11, xrTableCell10, xrTableCell14, xrTableCell21, xrTableCell24, xrTableCell31, xrTableCell33, xrTableCell20, xrTableCell2, lblOrderRef);
            if (tip == 0)
                this.PrintingSystem.EndPrint += new EventHandler(PrintingSystem_EndPrint);
        }

        public Etiket(string range1, int GelisPartisiId)
        {
            InitializeComponent();

            MyRange = GelisPartisiId.ToString();
            if (range1 != String.Empty)
                myData1.xEtiket.Merge(Session.DataManager.ExecuteDataTable("GetBarcodesYeni", range1, GelisPartisiId));  //TODO: DU4 için farklı değil! tüm etiketler tek seferde çıkıyor!

            MakeResizable(xrTableCell11, xrTableCell10, xrTableCell14, xrTableCell21, xrTableCell24, xrTableCell31, xrTableCell33, xrTableCell20, xrTableCell2, lblOrderRef);
            this.PrintingSystem.EndPrint += new EventHandler(PrintingSystem_EndPrint);
        }

        void PrintingSystem_EndPrint(object sender, EventArgs e)
        {
            Session.DataManager.ExecuteNonQuery("UpdGPBarcodeSet", MyRange);
        }


        #region MakeResizable
        Dictionary<string, Font> defaultFonts = new Dictionary<string, Font>();
        void MakeResizable(params XRControl[] controls)
        {
            foreach (XRTableCell cell in controls)
            {
                defaultFonts.Add(cell.Name, cell.Font);
                cell.BeforePrint += new PrintEventHandler(cell_BeforePrint);
            }
        }

        void cell_BeforePrint(object sender, PrintEventArgs e)
        {
            Resize((XRControl)sender);
        }

        private void Resize(XRControl cell)
        {
            //Resize ı table'larda düzgün yapan tek fonksiyon !!!
            Graphics gr = Graphics.FromHwnd(IntPtr.Zero);
            gr.PageUnit = GraphicsUnit.Millimeter;
            int factor = 10;

            Font defaultFont = defaultFonts[cell.Name];
            float newSize = defaultFont.Size;

            float stringWidth = gr.MeasureString(cell.Text, defaultFont).Width;
            float cellWidth = cell.WidthF;

            if (cellWidth < stringWidth * factor)
                newSize = defaultFont.Size * cell.Width / stringWidth / factor;

            Font newFont = new Font(defaultFont.Name, newSize, defaultFont.Style, defaultFont.Unit, defaultFont.GdiCharSet, defaultFont.GdiVerticalFont);

            cell.Font = newFont;

            gr.Dispose();
        }
        #endregion

        private static string MakeCriteria(string range)
        {
            string[] parts = range.Replace(" ", String.Empty).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            string str = String.Empty;
            foreach (string part in parts)
            {
                try
                {
                    int loc = part.IndexOf("-");
                    if (loc > -1)
                    {
                        int p1 = int.Parse("0" + part.Substring(0, loc).Replace("-", ""));
                        int p2 = int.Parse("0" + part.Substring(loc, part.Length - loc).Replace("-", ""));
                        if (p1 == 0 && p2 > 0)
                            str += " OR r.RollId <= " + p2.ToString();
                        else if (p1 > 0 && p2 == 0)
                            str += " OR r.RollId >= " + p1.ToString();
                        else
                            str += " OR r.RollId between " + p1.ToString() + " and " + p2.ToString();
                    }
                    else
                        str += " OR r.RollId = " + int.Parse(part).ToString();
                }
                catch
                {
                }
            }
            return str.Substring(4);
        }

        string lastProcessed = string.Empty;
        private void Etiket_PrintProgress(object sender, DevExpress.XtraPrinting.PrintProgressEventArgs e)
        {
            object x = GetCurrentRow();
            if (x != null)
            {
                System.Data.DataTable dt = ((System.Data.DataRowView)GetCurrentRow()).DataView.Table;
                string rollIds = string.Empty;
                foreach (System.Data.DataRow dr in dt.Rows)
                {
                    rollIds += dr["RollId"] + ",";
                }
                rollIds = rollIds.Substring(0, rollIds.Length - 1);

                if (lastProcessed != rollIds)
                {
                    Session.DataManager.ExecuteNonQuery("UpdOverProductionBarcodeSet", rollIds);
                    lastProcessed = rollIds;
                }
            }
        }
    }
}